package com.sapdroid.sapdroiddo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.util.Log;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.sapdroid.sapdroiddo.content.ItemTable;
import com.sapdroid.sapdroiddo.content.KeepDroidContentProvider;

public class TodoItemAdapter extends BaseAdapter {
	private static final String TAG = TodoItemAdapter.class.getName();
	private static final int EDIT = 0;
	private static final int DELETE = 1;
	private static final int DONE = 2;
	private final Context context;
	private final List<HashMap<String, String>> datas;

	private String selectedItemID;
	private ContentValues values;
	private final int section;

	public TodoItemAdapter(Context context, int section) {
		super();
		this.context = context;
		this.section = section;
		datas = new ArrayList<HashMap<String, String>>();
		datas.add(getDummyRow(0));
	}

	@Override
	public int getCount() {
		return datas.size();
	}

	@Override
	public Object getItem(int index) {
		return getDummyRow(index);
	}

	private HashMap<String, String> getDummyRow(int index) {
		HashMap<String, String> row = new HashMap<String, String>();
		row.put(ItemTable.COLUMN_ID, "DummyRow_ID");
		row.put(ItemTable.COLUMN_DESCRIPTION, "DummyRow Description");
		row.put(ItemTable.COLUMN_STATUS, "0");
		return row;
	}

	private HashMap<String, String> getRow(Cursor cursor) {
		HashMap<String, String> row = new HashMap<String, String>();
		row.put(ItemTable.COLUMN_ID, cursor.getString(cursor
				.getColumnIndex(ItemTable.COLUMN_ID)));
		row.put(ItemTable.COLUMN_DESCRIPTION, cursor.getString(cursor
				.getColumnIndex(ItemTable.COLUMN_DESCRIPTION)));
		row.put(ItemTable.COLUMN_STATUS, cursor.getString(cursor
				.getColumnIndex(ItemTable.COLUMN_STATUS)));
		return row;
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		Log.d(TAG, "get View " + position);

		if (convertView == null) {
			convertView = inflater.inflate(R.layout.todo_item, null);
		}
		final HashMap<String, String> row = datas.get(position);

		TextView textView = (TextView) convertView.findViewById(R.id.textView1);

		if (textView != null) {
			textView.setText(row.get(ItemTable.COLUMN_DESCRIPTION));
			textView.setTag(row.get(ItemTable.COLUMN_ID));
		}

		final View view = convertView;
		convertView.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);

				doLongPress(row);
				return false;
			}
		});

		return convertView;
	}

	protected void doLongPress(final HashMap<String, String> row) {
		// Get PopUp Menu Texts
		final String[] items = new String[] { context.getString(R.string.edit), context
				.getString(R.string.delete), context
				.getString(R.string.markdone) };
		// Get Selected ItemID
		selectedItemID = row.get(ItemTable.COLUMN_ID);
		values = new ContentValues();
		values.put(ItemTable.COLUMN_DESCRIPTION, row
				.get(ItemTable.COLUMN_DESCRIPTION));
		String tmp = row.get(ItemTable.COLUMN_STATUS);
		if (tmp == null) {
			tmp = "0";
		}
		values.put(ItemTable.COLUMN_STATUS, Integer.parseInt(tmp));
		// Show PopUp
		new AlertDialog.Builder(context).setItems(items, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				String where = ItemTable.COLUMN_ID + " = ?";
				switch (which) {
				case EDIT:
					// TODO :replace with callback
					((MainActivity) context).updateItem(row);
					break;

				case DELETE:
					int delRows = context
							.getContentResolver()
							.delete(KeepDroidContentProvider.CONTENT_URI_ITEM, where, new String[] { selectedItemID });
					// Items successful deleted
					if (delRows == 1) {
						Toast.makeText(context, "Item deleted", Toast.LENGTH_LONG)
								.show();
					} else {
						Toast.makeText(context, "Item not deleted", Toast.LENGTH_LONG)
								.show();
					}
					// TODO :replace with callback
					((MainActivity) context).reQuery();
					break;

				case DONE:
					int status = values.getAsInteger(ItemTable.COLUMN_STATUS);
					// Mark as done
					if (status == ItemTable.OPEN) {
						status = ItemTable.DONE;
					}
					// Mark as opem
					else {
						status = ItemTable.OPEN;
					}
					values.put(ItemTable.COLUMN_STATUS, status);
					int rows = context
							.getContentResolver()
							.update(KeepDroidContentProvider.CONTENT_URI_ITEM, values, where, new String[] { selectedItemID });
					if (rows == 1) {
						if (status == ItemTable.OPEN) {
							Toast.makeText(context, "Marked as open", Toast.LENGTH_LONG)
									.show();
						} else {
							Toast.makeText(context, "Marked as done", Toast.LENGTH_LONG)
									.show();
						}
					}

					// TODO :replace with callback
					((MainActivity) context).reQuery();

				}
			}
		}).show();
	}

	public void loadData(Cursor data) {
		datas.clear();
		for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
			datas.add(getRow(data));
		}
		notifyDataSetChanged();
	}

	public void setData(List<HashMap<String, String>> itemLists) {
		datas.clear();
		for (HashMap<String, String> item : itemLists) {
			int status = Integer.parseInt(item.get(ItemTable.COLUMN_STATUS));
			if (section == 0) {// OPEN
				if (status == ItemTable.OPEN) {
					datas.add(item);
				}
			} else if (section == 1) {// DONE
				if (status == ItemTable.DONE) {
					datas.add(item);
				}
			} else if (section == 2) {// All
				datas.add(item);
			}
		}
		notifyDataSetChanged();
	}

}